package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.domain.Category;
import com.spzx.product.mapper.CategoryMapper;
import com.spzx.product.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品分类Service业务层处理
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;


    @Override
    public List<Category> treeSelect(Long parentId) {
        List<Category> categoryList = categoryMapper.selectList(new LambdaQueryWrapper<Category>()
                .eq(Category::getParentId, parentId));

        if(!CollectionUtils.isEmpty(categoryList)){

            for (Category category : categoryList) {

                Long count = categoryMapper.selectCount(new LambdaQueryWrapper<Category>()
                        .eq(Category::getParentId, category.getId()));
                category.setHasChildren(count>0);
            }

        }

        return categoryList;
    }

    @Override
    public List<Long> getAllCategoryIdList(Long id) {
        List<Long> idList = new ArrayList<>();  //[1,2,3]  正序

        //存储顺序：逆序
        List<Category> categoryList =  this.getParentCategoryList(id,new ArrayList<Category>()); // [c3,c2,c1]
        int size = categoryList.size();
        for (int i = size-1; i >= 0 ; i--) {
            Category category = categoryList.get(i);
            idList.add(category.getId());
        }
        return idList;
    }

    /**
     * 递归：根据本级分类id,查询本级分类及所有上级分类数据；存储，逆序
     *     1.三级找二级、二级找一级 过程是同样过程
     *     2.一级找父亲没有了就结束了。
     *
     * @param id
     * @param categoryList
     * @return
     */
    private List<Category> getParentCategoryList(Long id, ArrayList<Category> categoryList) {
        while(id>0){
            Category category = categoryMapper.selectById(id); //本级
            categoryList.add(category);
            return getParentCategoryList(category.getParentId(),categoryList);
        }
        return categoryList;
    }
}